/**
 * @fileOverview forkAndLink
 * @author huangtonger@aliyun.com
 */

const Satellite = require('./satellite');
const Util = require('../../util/');

class ForkAndLink extends Satellite {
  getDefaultCfg() {
    return {
      /**
       * @type  {string} name - satellite name
       */
      name: 'forkAndLink',

      /**
       * @type  {function} render - satellite render
       * @param {object} diagram - diagram
       * @return {string|dom} dom or html
       */
      render(/* diagram */) {
        return `
          <div style="
            width: 11px;
            height: 11px;
            cursor: copy;
            background-image: url(https://gw.alipayobjects.com/zos/rmsportal/yWAiQOmucbYMCpwkvTBP.svg)
          "></div>
        `;
      },

      /**
       * @type  {function} render - satellite render
       * @param {object} dom - dom element
       * @param {object} diagram - diagram
       * @return {array} events
       */
      bindEvent(dom, diagram) {
        const graph = diagram.getGraph();
        const rootGroup = graph.getRootGroup();
        dom.setAttribute('draggable', 'true');
        const dragstart = Util.addEventListener(dom, 'dragstart', () => {
          const item = this.item;
          const tplModel = diagram.get('addEdgeModel');
          const addModel = {
            ...tplModel,
            source: item.id
          };
          const box = item.getBBox();
          const delegation = diagram.getDelegation([{ isEdge: true }], rootGroup);
          diagram.setSignal('dragEdge', true);
          diagram.beginAdd('edge', addModel);
          diagram.set('addEdgeConfig', {
            addModel,
            delegation,
            startPoint: {
              x: box.centerX,
              y: box.centerY
            },
            sourceItem: item
          });
          dom.hide();
        });
        const click = Util.addEventListener(dom, 'click', ({ clientX, clientY }) => {
          const editor = diagram.editor;
          const item = this.item;
          const point = graph.getPointByClient({
            x: clientX,
            y: clientY
          });
          const box = item.getBBox();
          const model = item.getModel();
          const v = [ point.x - box.centerX, point.y - box.centerY ];
          const vl = Util.vec2.length(v);
          Util.vec2.scale(v, v, 160 / vl);
          if (editor) {
            editor.executeCommand('copyAdjacent', {
              copyNode: item,
              x: point.x + v[0],
              y: point.y + v[1]
            });
          } else {
            const copyModel = Util.clone(model);
            copyModel.x = point.x + v[0];
            copyModel.y = point.y + v[1];
            graph.add(item.type, copyModel);
          }
        });
        return [ dragstart, click ];
      }
    };
  }
}
module.exports = ForkAndLink;

